// ignore_for_file: prefer_const_constructors, prefer_const_literals_to_create_immutables
import 'dart:convert';

import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';

import 'package:junyeyishu/widgets/QGWidget.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:junyeyishu/ui/bulletin/widgets/QGBulletinItem.dart';
import 'package:junyeyishu/utils/utils.dart';

class QGBulletinSearchPage extends StatefulWidget {
  String? text;
  QGBulletinSearchPage({super.key, this.text});
  @override
  State<QGBulletinSearchPage> createState() => _QGBulletinSearchPageState();
}

class _QGBulletinSearchPageState extends State<QGBulletinSearchPage> {
  var controller = TextEditingController();
  List<dynamic> recored = [];

  List<dynamic>? data;
  List<dynamic>? categories;

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }

  @override
  void initState() {
    super.initState();

    setupRecords();

    Network.post(url_anno_categ, data: {}).then((res) {
      if (!res.success) {
        toast(res.msg);
        return;
      }
      categories = res.data;
      // setState(() {});

      if (widget.text != null) {
        controller.text = widget.text ?? "";
        onSearch();
      }
    });
  }

  onRefresh(){}

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: [
           Column(
                    children: [
                      SizedBox(height: kSafeTop + 48.rpx),
                      Row(
                        children: [
                          SizedBox(width: 15,),
                          GestureDetector(
                            onTap: (){
                              Navigator.of(context).pop();
                            },
                            child: QGImage(asset: "nav_back_white",width: 20.rpx),
                          )
                          ,
                          SizedBox(width: 5,),
                          Expanded(child: 
                           buildSearchBar()
                          ),
                          SizedBox(width: 15,),

                        ],
                      ),
                 data == null ? buildRecord() : buildList()
            ],
           ),
        
        ],
      ),
    );
    
    // QGScaffold(
    //     bgColor: Color(0xFF0C1012),
    //     title: '',
    //     body: GestureDetector(
    //       onTap: () {
    //         unfocus(context);
    //       },
    //       child: Column(
    //         children: [
    //           // Container(height: 0.5.rpx, color: Color(0xFFEAEAEA)),
    //           SizedBox(height: 15.rpx),
    //           buildSearchBar(),
    //           data == null ? buildRecord() : buildList()
    //         ],
    //       ),
    //     ));
  }

  buildSearchBar() {
    return Stack(
      children: [
        Container(
          alignment: Alignment.center,
          margin: EdgeInsets.only(top: 0.rpx, left: 10.rpx, right: 10.rpx),
          child: Container(
            padding: EdgeInsets.only(left: 10.rpx),
            height: 40.rpx,
            decoration: BoxDecoration(
              color: Colors.transparent,
              borderRadius: BorderRadius.circular(26.rpx),
              border: Border.all(width: 1.rpx, color: Color(0xFFFFFFFF)),
            ),
            child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  QGImage(asset: "sale_search",width: 13.rpx),
                  TextButton(
                    onPressed: onSearch,
                    child: Text(
                      '搜索',
                      style: TextStyle(
                          color: Color(0xFFFFFFFF),
                          fontSize: 12.rpx,
                          fontWeight: FontWeight.normal),
                    ),
                  )
                ]),
          ),
        ),
        buildTextField()
      ],
    );
  }

  buildTextField() {
    return Positioned(
      left: 40,
      top: -7,
      right: 80,
      child: TextField(
          onChanged: (content) {
            if (content.isEmpty) {
              data = null;
              setState(() {});
            }
          },
          controller: controller,
          textInputAction: TextInputAction.done,
          cursorColor: Color(0xffFFFFFF),
          style: TextStyle(
              color: Color(0xffFFFFFF),
              fontSize: 12.rpx,
              fontWeight: FontWeight.bold),
          decoration: InputDecoration(
            hintText: "搜索公告内容",
            hintStyle: TextStyle(
              color: Color(0xff999999),
              fontSize: 12.rpx,
            ),
            enabledBorder: InputBorder.none,
            focusedBorder: InputBorder.none,
          )),
    );
  }

  buildRecord() {
    return Expanded(
      child: Container(
        padding: EdgeInsets.only(left: 20.rpx),
        child: Column(children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                '搜索记录',
                style: TextStyle(
                    color: Color(0xFFFFFFFF),
                    fontSize: 13.rpx,
                    fontWeight: FontWeight.bold),
              ),
              GestureDetector(
                onTap: clearRecords,
                child: Container(
                  color: Colors.transparent,
                  padding: EdgeInsets.all(20.rpx),
                  child: QGImage(asset: "bulletin_delete"),
                ),
              ),
            ],
          ),
          Expanded(
            child: SingleChildScrollView(
              child: Container(
                alignment: Alignment.centerLeft,
                child: Wrap(
                  spacing: 10.rpx,
                  runSpacing: 10.rpx,
                  children: buildRecordItems(),
                ),
              ),
            ),
          ),
        ]),
      ),
    );
  }

  buildRecordItems() {
    if (recored.isEmpty) {
      return [
        Center(
          child: Text(
            '没有搜索记录',
            style: TextStyle(
                color: Color(0xff999999),
                fontSize: 12.rpx,
                fontWeight: FontWeight.normal),
          ),
        ),
      ];
    }
    List<Widget> children = [];
    for (var item in recored) {
      children.add(buildRecordItem(item));
    }
    return children;
  }

  buildRecordItem(content) {
    return GestureDetector(
      onTap: () {
        controller.text = content;
        onSearch();
      },
      child: Container(
        // height: 26.rpx,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(6.rpx),
          color: Color(0xFFF8F8F6),
        ),
        padding: EdgeInsets.symmetric(horizontal: 10.rpx, vertical: 6.rpx),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              content ?? "",
              style: TextStyle(
                  color: Color.fromRGBO(17, 17, 17, 0.6),
                  fontSize: 12.rpx,
                  fontWeight: FontWeight.normal),
            ),
          ],
        ),
      ),
    );
  }

  setupRecords() async {
    final ins = await SharedPreferences.getInstance();
    final str = ins.getString('search_anno');

    try {
      recored = jsonDecode(str ?? "[]");
    } catch (e) {
      recored = [];
    }

    setState(() {});
  }

  updateRecords(key) async {
    if (recored.contains(key)) {
      recored.remove(key);
    }
    recored.insert(0, key);

    if (recored.length > 20) {
      recored.removeLast();
    }

    final ins = await SharedPreferences.getInstance();
    ins.setString('search_anno', jsonEncode(recored));
  }

  clearRecords() async {
    recored.clear();
    setState(() {});
    final ins = await SharedPreferences.getInstance();
    ins.remove("search_anno");
  }

  buildList() {
    if (data == null || data!.isEmpty) {
      return Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          SizedBox(height: 100.rpx),
          Text(
            '暂无内容',
            style: TextStyle(
                color: Color(0xff999999),
                fontSize: 12.rpx,
                fontWeight: FontWeight.normal),
          ),
        ],
      );
    }

    return Expanded(
      child: ListView.builder(
          padding: EdgeInsets.only(top: 20.rpx),
          itemCount: data?.length ?? 0,
          itemBuilder: (context, index) {
            var item = data?[index];
            if (item == null) {
              return Container();
            }
            var cate = categoryNameById(item["category_id"]);

            return GestureDetector(
                onTap: () {
                  toDetail(item, cate);
                },
                child: QGBulletinItem(data: item, cate: cate));
          }),
    );
  }

  categoryNameById(id) {
    if (categories == null) {
      return "";
    }
    for (var item in categories!) {
      if (item["id"] == id) {
        return item["name"];
      }
    }
  }

  onSearch() {
    unfocus(context);

    var keyword = controller.text;
    if (keyword.isEmpty) {
      toast("请输入内容");
      return;
    }

    updateRecords(keyword);

    var param = {};
    param['keyword'] = keyword;
    Map<String, dynamic> stringMap = param.cast<String, dynamic>();

    Network.post(url_anno, data: stringMap).then((res) {
      if (!res.success) {
        toast(res.msg);
        return;
      }
      data = res.data["data"];
      setState(() {});
    });
  }

  toDetail(data, cate) {
    var args = {"title": cate, "data": data};
    Navigator.of(context).pushNamed(PageNoticeDetial, arguments: args);
  }
}
